<?php
declare(strict_types=1);

namespace app\admin\quick\actions;


use app\common\model\SystemUser;
use app\common\model\SystemUserBalanceLog;
use app\common\model\SystemUserInfo;
use app\common\model\SystemUserIntegralLog;
use plugins\quickpay\model\QuickpayMerchant;
use plugins\quickpay\model\QuickpayMerchantIntegralLog;
use quick\admin\actions\RowAction;
use quick\admin\annotation\AdminAuth;
use quick\admin\form\Form;
use quick\admin\library\service\AuthService;
use quick\admin\library\tools\CodeTools;
use think\Request;

/**
 * 会员余额设置
 * @AdminAuth(title="会员余额设置",auth=true,login=true,menu=false)
 * @package app\admin\resource\example\actions
 */
class UserInfoBalanceAction extends RowAction
{

    public function init()
    {
        $this->getDisplay()->type("text");
        $this->name = "设置余额";
        $this->dialog();
    }


    public function form()
    {
        $form = Form::make("设置余额")->labelWidth(150);
        $form->radio("type", "设置类型")
            ->radioButton()
            ->options(['1' => "添加","2" => "减少"])->required();
        $form->text("number", "余额")->number(0.01,999999)
            ->rules("require");
        $form->text("desc","说明")->required();
        return $form;
    }

    public function resolve($request, $model)
    {

        $form = $this->form();
        $form->url($this->storeUrl());


        $form->props("extendData", [
            self::$keyName => $this->request->param(self::$keyName)
        ]);

        return $this->response()->success("success", $form);
    }

    public function handle($model, Request $request)
    {
        $form = $this->form();
        $data = (array)$form->getSubmitData($request, 3);
        $userInfo = SystemUserInfo::where('id', $model->id)->find();



        $this->startTrans();
        try {

            $changeNum = $data['number'];
            if($changeNum <= 0){
                throw new \Exception('变动数值有误，数值必须大于0');
            }
            if($data['type'] == 1){
                $desc = "系统充值余额：".$data['desc'];
                $userInfo->balance += $changeNum;
                $userInfo->total_balance += $changeNum;
            }else{
                $desc = "系统扣减余额：".$data['desc'];
                if($userInfo->balance <  $changeNum){
                    $changeNum = $userInfo->balance ;
                    $userInfo->balance = 0;
                    throw new \Exception('余额不够扣');
                }else{
                    $userInfo->balance -= $changeNum;
                }

            }
            if (!$userInfo->save()) {
                throw new \Exception($userInfo->getError());
            }
            $logModel = new  SystemUserBalanceLog();
            $logModel->user_id = $userInfo->user_id;
            $logModel->type = $data['type'];
            $logModel->num = $changeNum;
            $logModel->desc = $desc;
            $logModel->full_desc = json_encode([
                'admin_id' => AuthService::instance()->getAdminId(),
                'username' => AuthService::instance()->getUsername(),
            ]);
            $logModel->current_num = $userInfo->balance;
            $logModel->order_no = AuthService::instance()->getAdminId();
            $logModel->sign = 'admin';
            $logModel->created_at = date("Y-m-d H:i:s");
            if (!$logModel->save()) {
                throw new \Exception($logModel->getError());
            }
            $this->commit();
            $response = $this->response()->success("设置成功");
        }catch (\Exception $e){
            $this->rollback();
            $response = $this->response()->error("设置失败".$e->getMessage());
        }


        return $response;
    }


}
